package logic

import (
	"context"
	"fmt"
	"strconv"
	"usershop/api/pkg"
	"usershop/user_srv/user"

	"usershop/api/internal/svc"
	"usershop/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserNameLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginUserNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserNameLogic {
	return &LoginUserNameLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginUserNameLogic) LoginUserName(req *types.LoginNameUserRequest) (resp *types.ResMsg, err error) {
	// todo: 用户登录

	//获取用户信息
	red, err := l.svcCtx.UserSrv.GetUserInfoByUsername(l.ctx, &user.GetUserInfoByUsernameRequest{Username: req.Username})
	if err != nil {
		return &types.ResMsg{
			Cre:  -3,
			Msg:  "用户信息获取失败",
			Data: nil,
		}, nil
	}

	pwd := pkg.Md5String(req.Password + red.Salt) //密码加盐
	fmt.Print("加密后的密码...........", pwd)

	_, err = l.svcCtx.UserSrv.Log(l.ctx, &user.LoginNameUserRequest{
		Username: req.Username,
		Password: pwd,
	})

	if err != nil {
		return &types.ResMsg{
			Cre:  -1,
			Msg:  "登录失败",
			Data: nil,
		}, nil
	}

	token, err := pkg.GetJwtToken(strconv.FormatInt(red.UserId, 10))
	if err != nil {

		return &types.ResMsg{
			Cre:  -2,
			Msg:  "token生成失败",
			Data: nil,
		}, err
	}

	return &types.ResMsg{
		Cre: 0,
		Msg: "登录成功",
		Data: map[string]interface{}{
			"token": token,
		},
	}, nil
}
